<template>
  <div>
    <Row>
      <Card>
        <p slot="title">
          <Icon type="navicon-round"></Icon>
          渠道管理
        </p>
        <VmBtable type="edit" ref="VmBtable"
                  :columns="dataColumns"
                  :data="dataTable"
                  :searchparam="searchParam"
                  :importBtn="false"
                  :downTemplate="false"
                  :exportBtn="false"
                  :batchDelBtn="false"
                  :isControl="loginType === 'platform'"
                  :operate="operate"
                  placeholder="渠道名称关键字"
                  searchText="渠道名称："
                  cleanText="刷新"
                  @editFn="editFn"
                  @delete="deleteFn"
                  @configFn="configFn"
                  v-on:searchFn="searchFn"
                  v-on:page-change="pageChangeFn"
                  v-on:addFn="addFn"
                  v-on:restFn="restFn">
          <div slot="search" class="db_inline">

          </div>
        </VmBtable>
      </Card>
    </Row>
    <Modal v-model="modal.visible" :title="modal.title" v-on:on-ok="subForm" :mask-closable="false" width="680"
           v-on:on-cancel="cancelSub">
      <Row>
        <Form ref="schoolForm" :model="modal.form" :label-width="80" :rules="modal.rules">
          <FormItem label="名称" prop="name">
            <Input v-model="modal.form.name" placeholder="请输入名称" style="width:60%"/>
          </FormItem>
          <FormItem label="负责人" prop="chargePerson">
            <Input v-model="modal.form.chargePerson" placeholder="请输入负责人" style="width:60%"/>
          </FormItem>
          <FormItem label="联系号码" prop="phone">
            <Input v-model="modal.form.phone" placeholder="请输入联系号码" style="width:60%"/>
          </FormItem>
          <FormItem class="db_inline" label="地址" v-if="!modal.isEdit" prop="countyId">
            <Select v-model="modal.form.provinceId" label-in-value @on-change="provinceChange" style="width:100px">
              <Option v-for="item in area.provinceList" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
            <Select v-model="modal.form.cityId" label-in-value @on-change="cityChange" style="width:100px">
              <Option v-for="item in area.cityList" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
            <Select v-model="modal.form.countyId" label-in-value @on-change="countyChange" style="width:130px">
              <Option v-for="item in area.countyList" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="详细地址" prop="detailAddress">
            <Input v-model="modal.form.detailAddress" placeholder="请输入详细地址" style="width:60%"/>
          </FormItem>
          <FormItem label="备注" prop="remark">
            <Input v-model="modal.form.remark" type="textarea" placeholder="备注信息" style="width:60%"/>
          </FormItem>
        </Form>
      </Row>
      <div slot="footer">
        <Button type="text" @click="cancelSub">取消</Button>
        <Button type="primary" @click="subForm" :loading="modal.loading">确定</Button>
      </div>
    </Modal>
    <Modal v-model="wechat.visible" :title="wechat.title" v-on:on-ok="sureConfig" :mask-closable="false" width="580"
           v-on:on-cancel="cancelConfig">
      <Form ref="wechatForm" :model="wechat.form" :label-width="120" :rules="wechat.rules">
        <FormItem label="appId" prop="appId">
          <Input v-model="wechat.form.appId" placeholder="请输入微信appId" style="width:73%"/>
        </FormItem>
        <FormItem label="secret" prop="secret">
          <Input v-model="wechat.form.secret" placeholder="请输入微信secret" style="width:73%"/>
        </FormItem>
        <FormItem label="商户ID" prop="mchId">
          <Input v-model="wechat.form.mchId" placeholder="请输入商户ID" style="width:73%"/>
        </FormItem>
        <FormItem label="商户秘钥" prop="apiKey">
          <Input v-model="wechat.form.apiKey" placeholder="请输入商户秘钥" style="width:73%"/>
        </FormItem>
        <FormItem label="域名" prop="domain">
          <Input v-model="wechat.form.domain" placeholder="请输入服务器域名" style="width:73%"/>
        </FormItem>
        <FormItem label="报告模板ID" prop="uhTemplateId">
          <Input v-model="wechat.form.uhTemplateId" placeholder="请输入微信secret" style="width:73%"/>
        </FormItem>
        <FormItem label="请假模板ID" prop="leaveApplyTemplateId">
          <Input v-model="wechat.form.leaveApplyTemplateId" placeholder="请输入微信secret" style="width:73%"/>
        </FormItem>
        <FormItem label="审核通过模板ID" prop="judePassTemplateId">
          <Input v-model="wechat.form.judePassTemplateId" placeholder="请输入微信secret" style="width:73%"/>
        </FormItem>
        <FormItem label="校验文件" v-if="wechat.showValidTxt" prop="validTxt">
          <Upload
            style="width:73%"
            accept=".txt"
            type="drag"
            :data="{token:uploadToken}"
            :on-remove="removeValidTxt"
            :on-success="uploadSuccess"
            :action="action">
            <div style="padding: 20px 0">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              <p>选择校验文件</p>
            </div>
          </Upload>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelConfig">取消</Button>
        <Button type="primary" @click="sureConfig" :loading="wechat.loading">确定</Button>
      </div>
    </Modal>
    <Modal v-model="account.visible" :title="account.title" v-on:on-ok="sureEdit" v-on:on-cancel="cancelEdit"
           :mask-closable="false" width="350">
      <Form ref="accountForm" :model="account.form" :label-width="80" :rules="account.rules">
        <FormItem label="登录名" prop="adminAccount">
          <Input v-model="account.form.adminAccount" placeholder="请输入登录名" style="width:73%"/>
        </FormItem>
        <strong>注：</strong>账号只能修改一次！
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelEdit">取消</Button>
        <Button type="primary" @click="sureEdit" :loading="account.loading">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import API from "@/api/api";
  import VmBtable from "@/components/vm/vm-btable";
  import Cookie from "js-cookie"

  export default {
    components: {
      VmBtable
    },
    data() {
      const phoneValidate = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入联系人电话'));
        }else {
          callback();
        }
      };
      return {
        searchParam: {
          current: 1,
          size: 20,
          total: 0,
          name: '',
          merchantType: 'channel'
        },
        dataColumns: [
          {
            title: '序号',
            type: 'index',
            align: 'center',
            minWidth: 100,
          },
          {
            title: '名称',
            align: 'center',
            key: 'name',
            minWidth: 200,
          },
          {
            title: '负责人',
            align: 'center',
            key: 'chargePerson',
            minWidth: 200,
          },
          {
            title: '管理员账号',
            align: 'center',
            key: 'adminAccount',
            minWidth: 200,
            render: (h, param) => {
              let account = param.row.adminAccount;
              let admin = account ? account : '无(点击新增)';
              return h('div', {
                style: {
                  color: 'blue',
                  cursor: 'pointer',
                },
                on: {
                  click: () => {
                    this.editAdmin(param.row)
                  }
                }
              }, admin);
            }
          },
          {
            title: '联系号码',
            align: 'center',
            key: 'phone',
            minWidth: 200,
          },
          {
            title: '创建时间',
            align: 'center',
            key: 'createTime',
            minWidth: 200,
          },
          {
            title: '创建人',
            align: 'center',
            key: 'createByName',
            minWidth: 200,
          },
          {
            title: '操作',
            type: "operation",
            minWidth: 200,
            render: (h, param) => {
              let loginType = this.loginType;
              let operation = [];
              let edit = h('Button', {
                props: {type: 'info', size: 'small'},
                style: {marginRight: '5px'},
                on: {
                  click: () => {
                    this.editFn(param.row)
                  }
                }
              }, '编辑');
              let wechantConfig = h('Button', {
                props: {type: 'info', size: 'small'},
                style: {marginRight: '5px'},
                on: {
                  click: () => {
                    this.configFn(param.row)
                  }
                }
              }, '微信配置');
              let deleteFn = h('Button', {
                props: {type: 'error', size: 'small'},
                style: {marginRight: '5px'},
                on: {
                  click: () => {
                    this.deleteFn(param.row)
                  }
                }
              }, '删除');
              if (param.row.init) {
                operation = [edit]
              } else {
                if (loginType === 'channel') {
                  operation = [edit]
                } else if (loginType === 'platform') {
                  operation = [edit, deleteFn];
                }
              }
              return h('div', {}, operation);
            }
          }
        ],
        operate: [],
        dataTable: [],
        action: Cookie.getJSON('uploadServer'),
        uploadToken: Cookie.getJSON('uploadToken'),
        loginType: Cookie.getJSON('loginType'),
        area: {
          provinceList: [],
          cityList: [],
          countyList: [],
          parentId: 0,
        },
        modal: {
          visible: false,
          loading: false,
          isEdit: false,
          title: '',
          form: {
            id: '',
            chargePerson: '',
            name: '',
            provinceId: '',
            provinceName: '',
            cityId: '',
            cityName: '',
            countyId: '',
            countyName: '',
            detailAddress: '',
            remark: '',
          },
          rules: {
            'name': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'chargePerson': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'phone': [{
              required: true,
              validator: phoneValidate,
              trigger: 'blur',
            }],
            'countyId': [{
              type: 'number',
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'detailAddress': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
          }
        },
        wechat: {
          visible: false,
          title: '',
          loading: false,
          showValidTxt: true,
          form: {
            id: '',
            appId: '',
            secret: '',
            domain: '',
            merchantId: '',
            validTxt: '',
            uhTemplateId: '',
            leaveApplyTemplateId: '',
            judePassTemplateId: '',
            mchId: '',
            apiKey: '',
          },
          rules: {
            'appId': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'secret': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'domain': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'uhTemplateId': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'leaveApplyTemplateId': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'judePassTemplateId': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'validTxt': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'mchId': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
            'apiKey': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
          }
        },
        account: {
          visible: false,
          title: '',
          loading: false,
          oldAccount: '',
          form: {
            adminAccount: '',
          },
          rules: {
            "adminAccount": [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }],
          }
        }
      };
    },
    methods: {
      editAdmin(channel) {
        this.account.oldAccount = channel.adminAccount;
        Object.assign(this.account, {
          visible: true,
          title: '编辑【' + channel.name + '】管理员',
        });
        Object.assign(this.account.form, channel);
      },
      sureEdit() {
        this.$refs.accountForm.validate(valid => {
          if (valid) {
            if (this.account.oldAccount === this.account.form.adminAccount) {
              this.$Message.warning('新账号不能和原账号相同');
              return;
            }
            this.account.loading = true;
            API.updateMerchantAccount(this.account.form).then(resp => {
              this.queryFn();
              Object.assign(this.account, {
                visible: false,
                loading: false,
              })
            }).catch(resp => {
              this.account.loading = false;
            })
          }
        })
      },
      cancelEdit() {
        Object.assign(this.account, {
          visible: false,
          loading: false,
        })
      },
      getUploadFile(oldList, newFile) {
        this.modal.form.logo = newFile.name;
      },
      addFn() {
        Object.assign(this.modal, {
          visible: true,
          title: '添加',
          isEdit: false,
          form: {}
        });
      },
      editFn(data) {
        Object.assign(this.modal, {
          visible: true,
          title: '编辑【' + data.name + '】',
          isEdit: true,
        });
        Object.assign(this.modal.form, data);
      },
      deleteFn(data) {
        this.$Modal.confirm({
          title: '警告',
          content: '是否删除该渠道数据？',
          onOk: () => {
            this.$Spin.show({
              render: (h) => {
                return h('div', [
                  h('Icon', {
                    'class': 'demo-spin-icon-load',
                    props: {
                      type: 'load-c',
                      size: 18
                    }
                  }),
                  h('div', '删除中...')
                ])
              }
            });
            API.deleteMerchant(data.id).then(resp => {
              this.queryFn();
              this.$Spin.hide();
            })
          }
        });
      },
      configFn(data) {
        Object.assign(this.wechat, {
          visible: true,
          title: '配置【' + data.name + '】'
        });
        this.wechat.form.merchantId = data.id;
        API.fetchMerchantConfig(data.id).then(resp => {
          if (resp.data) {
            this.wechat.showValidTxt = false;
            this.wechat.form = resp.data;
          } else {
            this.wechat.showValidTxt = true;
          }
        })
      },
      restFn() {
        this.searchParam.current = 1;
        this.searchParam.size = 20;
        this.searchParam.name = '';
        this.queryFn();
      },
      queryFn() {
        API.fetchMerchant(this.searchParam).then(
          res => {
            let data = res.data;
            this.dataTable = data.records;
            this.searchParam.total = data.total;
          },
          error => {
            this.$Message.info(error.msg);
          }
        );
      },
      complete() {
        Object.assign(this.modal, {
          loading: false,
          visible: false,
        });
        this.$refs.schoolForm.resetFields();
      },
      subForm() {
        this.$refs.schoolForm.validate(valid => {
          if (valid) {
            this.modal.loading = true;
            let data = Object.assign(this.modal.form);
            if (data.id) {
              API.updateMerchant(data).then(resp => {
                this.complete();
                this.queryFn();
              })
            } else {
              this.modal.form.merchantType = 'channel'
              API.createMerchant(data).then(resp => {
                this.complete();
                this.queryFn();
              })
            }
          }
        })
      },
      cancelSub() {
        this.complete();
      },
      pageChangeFn(current) {
        this.searchParam.current = current;
        this.queryFn();
      },
      searchFn(value) {
        this.searchParam.name = value;
        this.queryFn();
      },
      fetchProvince() {
        API.fetchArea(0).then(resp => {
          this.area.provinceList = resp.data;
        })
      },
      fetchCity(provinceId) {
        API.fetchArea(provinceId).then(resp => {
          this.area.cityList = resp.data;
        })
      },
      fetchCounty(cityId) {
        API.fetchArea(cityId).then(resp => {
          this.area.countyList = resp.data;
        })
      },
      provinceChange(obj) {
        this.modal.form.cityId = '';
        this.modal.form.countyId = '';
        if (obj) {
          this.modal.form.provinceName = obj.label;
          this.fetchCity(obj.value);
        }
      },
      cityChange(obj) {
        this.modal.form.countyId = '';
        if (obj) {
          this.modal.form.cityName = obj.label;
          this.fetchCounty(obj.value);
        }
      },
      countyChange(obj) {
        if (obj) {
          this.modal.form.countyName = obj.label;
        }
      },
      sureConfig() {
        this.$refs.wechatForm.validate(valid => {
          if (valid) {
            this.wechat.loading = true;
            let data = Object.assign(this.wechat.form);
            API.setMerchantConfig(data).then(resp => {
              Object.assign(this.wechat, {
                loading: false,
                visible: false,
              })
            })
          }
        })
      },
      cancelConfig() {
        Object.assign(this.wechat, {
          loading: false,
          visible: false,
        })
        this.$refs.wechatForm.resetFields();
      },
      removeValidTxt(resp, fileList) {
        API.deleteFileFromQiNiu({fileName: resp.response.key}).then(resp => {
          this.wechat.form.validTxt = '';
        });
      },
      uploadSuccess(response, file, fileList) {
        this.wechat.form.validTxt = response.key;
      }
    },
    mounted() {
      this.queryFn();
      this.fetchProvince();
    }
  }
</script>

<style scoped>

</style>
